package order

import (
	"context"
	"errors"
	"group-buy/group_buy/internal/models"
	"time"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderNotifyLogic {
	return &OrderNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderNotifyLogic) OrderNotify(req *types.OrderNotifyReq) error {
	order := &models.Order{PayOrderId: req.PayOrderId}
	get, err := l.svcCtx.Engine.Get(order)
	if err != nil {
		return err
	}
	if !get {
		return errors.New("订单不存在")
	}
	order.Status = 2
	order.PayTime = time.Now().Format(time.DateTime)
	_, _ = l.svcCtx.Engine.ID(order.Id).Update(order)

	_, _ = l.svcCtx.Engine.Where("order_code=?", order.Code).Update(&models.OrderDivision{DivStatus: 2, DivTime: time.Now().Format(time.DateTime), OrderId: order.Id})

	if order.InviteId > 0 {
		// region 添加到购买者成为邀请人的下级
		exist, _ := l.svcCtx.Engine.Exist(&models.BusinessMember{MemberId: order.UserId, BusinessId: order.BusinessId, InviteId: order.InviteId})
		if !exist {
			member := &models.Member{Id: order.UserId}
			get, err = l.svcCtx.Engine.Get(member)
			if err != nil {
				return err
			}
			if !get {
				return errors.New("会员不存在")
			}
			business := &models.Business{Id: order.BusinessId}
			get, err = l.svcCtx.Engine.Get(business)
			if err != nil {
				return err
			}
			if !get {
				return errors.New("门店不存在")
			}
			_, err = l.svcCtx.Engine.InsertOne(&models.BusinessMember{
				Id:             0,
				MemberId:       order.UserId,
				MemberName:     order.UserName,
				MemberPhone:    member.Phone,
				BusinessId:     order.BusinessId,
				BusinessName:   business.Name,
				InviteId:       order.InviteId,
				IsIndependence: 0,
			})
			if err != nil {
				return err
			}
		}
		// endregion

		//region 修改邀请人推广次数
		inviteBm := &models.BusinessMember{MemberId: order.InviteId, BusinessId: order.BusinessId}
		get, err = l.svcCtx.Engine.Get(inviteBm)
		if err != nil {
			return err
		}
		if get {
			count, err := l.svcCtx.Engine.Where("invite_id=? and business_id=? and status>1", order.InviteId, order.BusinessId).Count(&models.Order{})
			if err != nil {
				return err
			}
			if count >= 2 {
				inviteBm.IsIndependence = 1
			} else {
				inviteBm.IsIndependence = 2
			}

			_, err = l.svcCtx.Engine.ID(inviteBm.Id).Update(inviteBm)
			if err != nil {
				return err
			}
		} else {
			member := &models.Member{Id: order.InviteId}
			get, err = l.svcCtx.Engine.Get(member)
			if err != nil {
				return err
			}
			if !get {
				return errors.New("会员不存在")
			}
			business := &models.Business{Id: order.BusinessId}
			get, err = l.svcCtx.Engine.Get(business)
			if err != nil {
				return err
			}
			if !get {
				return errors.New("门店不存在")
			}
			_, err = l.svcCtx.Engine.InsertOne(&models.BusinessMember{
				Id:             0,
				MemberId:       member.Id,
				MemberName:     member.Name,
				MemberPhone:    member.Phone,
				BusinessId:     business.Id,
				BusinessName:   business.Name,
				InviteId:       0,
				IsIndependence: 2,
			})
			if err != nil {
				return err
			}
		}

		//endregion

	}

	// info, err := order.GetOrderDivision(l.svcCtx.Engine)
	// if err != nil {
	// 	return err
	// }
	// info, err := division.GetDivisionInfo(l.svcCtx.Engine)
	// if err != nil {
	// 	division.StatusMsg = err.Error()
	// 	_, _ = l.svcCtx.Engine.ID(division.Id).Update(division)
	// 	return err
	// }

	// extra := &request_models.DivisionExtra{
	// 	ChannelUser: "0",
	// 	DivInfos:    info,
	// }

	// lsDivision := &request_models.LsDivision{
	// 	MchNo:        l.svcCtx.Config.LsPay.MchNo,
	// 	AppId:        l.svcCtx.Config.LsPay.AppId,
	// 	MchOrderNo:   common.GetStrId(),
	// 	WayCode:      "BALANCE_PAY",
	// 	Amount:       int64(order.Amount * 100),
	// 	Currency:     "cny",
	// 	Subject:      "分润",
	// 	Body:         "分润",
	// 	NotifyUrl:    "",
	// 	ChannelExtra: extra,
	// 	DivisionMode: 1,
	// 	ReqTime:      common.GetIntId(),
	// 	Version:      "1.0",
	// 	SignType:     "MD5",
	// }
	// rsp, err := lsDivision.Division(l.svcCtx.Config.LsPay.PayKey)
	// if err != nil {
	// 	division.StatusMsg = err.Error()
	// 	_, _ = l.svcCtx.Engine.ID(division.Id).Update(division)
	// 	return err
	// }
	// if rsp.Status == 200 {
	// 	if rsp.Data.TransStatus == "S" {
	// 		division.Status = "ok"
	// 		division.StatusMsg = "ok"
	// 		_, _ = l.svcCtx.Engine.ID(division.Id).Update(division)
	// 	} else {
	// 		division.StatusMsg = rsp.Data.ErrMsg
	// 		_, _ = l.svcCtx.Engine.ID(division.Id).Update(division)
	// 	}
	// } else {
	// 	division.StatusMsg = rsp.Msg
	// 	_, _ = l.svcCtx.Engine.ID(division.Id).Update(division)
	// }

	return nil
}
